package com.huffman.smart_picture.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huffman.smart_picture.common.auth.AuthConstant;
import com.huffman.smart_picture.common.auth.annotation.CheckRole;
import com.huffman.smart_picture.common.UserSession;
import com.huffman.smart_picture.common.base.request.BatchDeleteRequest;
import com.huffman.smart_picture.common.base.reponse.PageQueryResult;
import com.huffman.smart_picture.common.base.reponse.ResponseResult;
import com.huffman.smart_picture.common.base.request.BatchUpdateRequest;
import com.huffman.smart_picture.common.base.request.UpdateRequest;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.domain.constants.CommonConstant;
import com.huffman.smart_picture.domain.entity.User;
import com.huffman.smart_picture.domain.request.user.UserInsertRequest;
import com.huffman.smart_picture.domain.request.user.UserPageQueryRequest;
import com.huffman.smart_picture.domain.request.user.UserUpdateRequest;
import com.huffman.smart_picture.domain.vo.user.UserVo;
import com.huffman.smart_picture.service.UserService;
import com.huffman.smart_picture.service.VipExchangeCodeService;
import com.huffman.smart_picture.utils.ResponseUtil;
import com.huffman.smart_picture.utils.ThrowUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author DengLin
 * @title 用户增删改查
 * @date 2024/07/03
 */
//@Api(tags = "用户增删改查")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    VipExchangeCodeService vipExchangeCodeService;

    @GetMapping("/search/{id}")
    @ApiOperation(value = "查询用户信息")
    public ResponseResult<UserVo> searchUser(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        UserVo userVo = UserVo.convert(user);
        return ResponseUtil.success(userVo);
    }

    @PostMapping("/insert")
    @ApiOperation(value = "添加用户")
    public ResponseResult insertUser(@RequestBody UserInsertRequest userInsertRequest) {
        User user = UserInsertRequest.convert(userInsertRequest);
        user.setPassword(userService.encryptPassword(userInsertRequest.getPassword()));
        userService.save(user);
        return ResponseUtil.success();
    }


    @PostMapping("/delete/{id}")
    @ApiOperation(value = "删除用户")
    public ResponseResult deleteUser(@PathVariable("id") Long id) {
        userService.removeById(id);
        return ResponseUtil.success();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新用户")
    public ResponseResult updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        User user = UserUpdateRequest.convert(userUpdateRequest);
        userService.updateById(user);
        return ResponseUtil.success();
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult pageQuery(UserPageQueryRequest pageQueryUserRequest, HttpServletRequest request) {
        UserSession userSession = (UserSession) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        Integer pageNum = pageQueryUserRequest.getPageNum();
        Integer pageSize = pageQueryUserRequest.getPageSize();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        String username = pageQueryUserRequest.getUsername();
        String nickname = pageQueryUserRequest.getNickname();
        String phone = pageQueryUserRequest.getPhone();
        String email = pageQueryUserRequest.getEmail();
        Integer status = pageQueryUserRequest.getStatus();
        String sortField = pageQueryUserRequest.getSortField();
        String sort = pageQueryUserRequest.getSort();
        if (userSession != null) {
            // 去掉自己
            userQueryWrapper.ne(userSession.getId() != null, "id", userSession.getId());
        }
        userQueryWrapper
                // 排除管理员
                .ne("role", CommonConstant.ADMIN)
                .like(StringUtils.hasText(username), "username", username)
                .like(StringUtils.hasText(nickname), "nickname", nickname)
                .like(StringUtils.hasText(phone), "phone", phone)
                .like(StringUtils.hasText(email), "email", email)
                .eq(Objects.nonNull(status), "status", status)
                .orderBy(StringUtils.hasText(sortField), CommonConstant.SORT_ASC.equals(sort), sortField);
        Page<User> page = new Page<>(pageNum, pageSize);
        userService.page(page, userQueryWrapper);
        List<UserVo> userVoList = page.getRecords().stream().map(UserVo::convert).collect(Collectors.toList());
        PageQueryResult<UserVo> pageQueryResult = new PageQueryResult<>();
        pageQueryResult.setData(userVoList);
        pageQueryResult.setPages(page.getPages());
        pageQueryResult.setTotal(page.getTotal());
        return ResponseUtil.success(pageQueryResult);
    }

    @PostMapping("/batch/delete")
    @ApiOperation(value = "批量删除用户")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult deleteUsers(@RequestBody BatchDeleteRequest batchDeleteRequest) {
        userService.removeBatchByIds(batchDeleteRequest.getIds());
        return ResponseUtil.success();
    }

    @PostMapping("/batch/update")
    @ApiOperation(value = "批量更新用户")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult updateUsers(@RequestBody BatchUpdateRequest<UserUpdateRequest> batchUpdateRequest) {
        List<User> userList = batchUpdateRequest.getData().stream().map(UserUpdateRequest::convert).collect(Collectors.toList());
        userService.updateBatchById(userList);
        return ResponseUtil.success();
    }

    @PostMapping("/ban")
    @ApiOperation(value = "禁用用户")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult banUser(@RequestBody UpdateRequest updateRequest) {
        ThrowUtil.throwIf(updateRequest == null, ErrorEnum.PARAM_EMPTY, "请求体为空");
        boolean res = userService.banUser(updateRequest.getId());
        return ResponseUtil.success(res);
    }

    @PostMapping("/unban")
    @ApiOperation(value = "解封用户")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult unbanUser(@RequestBody UpdateRequest updateRequest) {
        ThrowUtil.throwIf(updateRequest == null, ErrorEnum.PARAM_EMPTY, "请求体为空");
        boolean res = userService.unbanUser(updateRequest.getId());
        return ResponseUtil.success(res);
    }
}
